#!/usr/bin/perl 

use strict;
use LWP::Simple;

my $compile = shift(@ARGV) =~ /-.*s/ ? 0 : 1;

my $org = "These documents can be originally found at http://insti.physics.sunysb.edu/latex-help/LaTeX.html. More information can be found in the info.html file.\nThe original was created by George Greenwade as a VMS help file. It was compiled by Norman Walsh, and downloaded locally by Vincenzo Carrino.";

my $base = 'http://insti.physics.sunysb.edu/latex-help/ltx-'; 
my $i = 2;
my $end  = '.html';

mkdir 'Latex Ref' or warn 'Can not make directory';
chdir 'Latex Ref' or die 'Can not change directory';

my $intro = get('http://insti.physics.sunysb.edu/latex-help/LaTeX.html');
my $info = get('http://insti.physics.sunysb.edu/latex-help/LaTeX-info.html');
print "Downloading: Intro, Info\n";
{open my $F, '>', 'intro.html';
    $intro =~ s/HREF="/HREF="Files\//g;
    print $F $intro; close $F;}
{open my $F, '>', 'info.html'; print $F $info; close $F;}
{open my $F, '>', 'org.txt'; print $F $org; close $F;}

mkdir 'Files' or warn 'Can not make directory';
chdir 'Files' or die 'Can not change directory';

{open my $F, '>', 'LaTeX-info.html'; print $F $info; close $F;}

my $ALL;
if($compile){
    open $ALL , '>', 'compiled.html';
    $info =~ s/HREF=".+?(\d+).+?"/HREF="#$1"/g;
    $intro =~ s/HREF=".+?(\d+).+?"/HREF="#$1"/g;
    print $ALL $intro . $info;
}

while(my $data = get("$base$i$end")){
    print "Downloading Page: $i\n";
    open my $F, '>', "ltx-$i.html";
    print $F $data;
    if($compile){
        $data =~ s/HREF=".+?(\d+).+?"/HREF="#$1"/g;
        $data =~ s/<BODY>/<BODY>\n<a name="$i"><\/a>/;
        print $ALL $data;
    }
    close $F;
    $i++;
}
close $ALL if $compile;
